<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form :model="queryForm" inline ref="form">
        <el-form-item label="审批状态" prop="applyState">
          <el-select v-model="queryForm.applyState">
            <el-option value="" label="全部"></el-option>
            <el-option :value="1" label="待审批"></el-option>
            <el-option :value="2" label="审批中"></el-option>
            <el-option :value="3" label="审批拒绝"></el-option>
            <el-option :value="4" label="审批通过"></el-option>
            <el-option :value="5" label="作废"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="table-btn">
        <el-button v-has="'user-add'" type="primary" @click="handleApply"
          >申请休假</el-button
        >
      </div>
      <el-table
        :data="leaveList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in column"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleDetail(scope.row)"
              >查看</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row._id)"
              >作废</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      title="申请休假"
      :before-close="handleClose"
      width="70%"
    >
      <el-form
        label-width="100px"
        :model="leaveForm"
        :rules="rules"
        ref="dialogForm"
      >
        <el-form-item required label="休假类型" prop="applyType">
          <el-select v-model="leaveForm.applyType">
            <el-option label="事假" :value="1"></el-option>
            <el-option label="调休" :value="2"></el-option>
            <el-option label="年假" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="休假日期">
          <el-row>
            <el-col :span="8">
              <el-form-item prop="startTime" required>
                <el-date-picker
                  v-model="leaveForm.startTime"
                  type="date"
                  placeholder="请选择开始日期"
                  @change="(val) => handleDateChange('startTime', val)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="1">-</el-col>
            <el-col :span="8">
              <el-form-item prop="endTime" required>
                <el-date-picker
                  v-model="leaveForm.endTime"
                  type="date"
                  placeholder="请选择结束日期"
                  @change="(val) => handleDateChange('endTime', val)"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="休假时长" prop="leaveTime" required>
          {{ leaveForm.leaveTime }}
        </el-form-item>
        <el-form-item label="休假原因" prop="reasons" required>
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入休假的原因"
            v-model="leaveForm.reasons"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="申请休假详情" width="50%" v-model="showDetailModel">
      <el-steps
        :active="detail.applyState > 2 ? 3 : detail.applyState"
        finish-status="success"
      >
        <el-step title="待审批"></el-step>
        <el-step title="审批中"></el-step>
        <el-step title="审批完成"></el-step>
      </el-steps>
      <el-form label-width="120px" label-suffix=":">
        <el-form-item label="休假类型">
          <div>{{ detail.applyType }}</div>
        </el-form-item>
        <el-form-item label="休假时间">
          <div>{{ detail.time }}</div>
        </el-form-item>
        <el-form-item label="休假时长">
          <div>{{ detail.leaveTime }}</div>
        </el-form-item>
        <el-form-item label="休假原因">
          <div>{{ detail.reasons }}</div>
        </el-form-item>
        <el-form-item label="审批状态">
          <div>{{ detail.applyStateName }}</div>
        </el-form-item>
        <el-form-item label="审批人">
          <div>{{ detail.curAuditUserName }}</div>
        </el-form-item>
        <!-- <el-form-item label="当前审批人">
          <div>{{ detail.applyStateName }}</div>
        </el-form-item> -->
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, getCurrentInstance, toRaw } from "vue";
import utils from "../../utils/utils";
export default {
  name: "User",
  setup() {
    //获取this实例
    const { proxy } = getCurrentInstance();

    //生命周期
    onMounted(() => {
      getLeaveList();
    });

    const handleDateChange = (key, val) => {
      let { startTime, endTime } = leaveForm;
      if (!startTime || !endTime) return;
      if (startTime > endTime) {
        proxy.$message.error("开始日期不能晚于结束日期");
        leaveForm.leaveTime = "0天";
        leaveForm[key] = "";
      } else {
        leaveForm.leaveTime =
          (endTime - startTime) / (24 * 60 * 60 * 1000) + 1 + "天";
      }
    };

    const queryForm = reactive({
      applyState: "",
    });

    // 查询用户数据
    const handleQuery = () => {
      getLeaveList();
    };

    // 重置查询
    const handleReset = (form) => {
      proxy.$refs[form].resetFields();
    };

    // 处理分页变化
    const handleCurrentChange = (current) => {
      pager.pageNum = current;
      getLeaveList();
    };

    // 点击删除单个用户
    const handleDelete = async (_id) => {
      try {
        let parmas = { _id, action: "delete" };
        await proxy.$api.leaveOperate(parmas);
        proxy.$message.success("删除成功");
        getLeaveList();
      } catch (error) {}

      // if (res.modifiedCount > 0) {
      //   proxy.$message.success(`成功删除${res.modifiedCount}条数据！`);
      // } else {
      //   proxy.$message.error(`删除失败！`);
      // }
    };

    const handleSelectionChange = (list) => {
      let arr = [];
      list.forEach((element) => {
        arr.push(element.userId);
      });
      checkedUsersIds.value = arr;
    };

    /**数据定义 */
    // const userList = reactive({
    //   arr:[]
    // }); //引用数据类型

    const column = reactive([
      {
        label: "单号",
        prop: "orderNo",
      },
      {
        label: "休假时间",
        prop: "applyTime",
        formatter(row) {
          return (
            utils.formateDate(new Date(row.startTime), "yyyy-MM-dd") +
            "到" +
            utils.formateDate(new Date(row.endTime), "yyyy-MM-dd")
          );
        },
      },
      {
        label: "休假时长",
        prop: "leaveTime",
      },
      {
        label: "休假类型",
        prop: "applyType",
        formatter(row, column, value) {
          return {
            1: "事假",
            2: "调休",
            3: "年假",
          }[value];
        },
      },
      {
        label: "休假原因",
        prop: "reasons",
      },
      {
        label: "申请时间",
        prop: "createTime",
        formatter(row, column, value) {
          return utils.formateDate(new Date(value));
        },
      },
      {
        label: "审批人",
        prop: "auditUser",
      },
      {
        label: "当前审批人",
        prop: "curAuditUserName",
      },
      {
        label: "审批状态",
        prop: "applyState",
        formatter(row, column, value) {
          return {
            1: "待审批",
            2: "审批中",
            3: "审批拒绝",
            4: "审批通过",
            5: "作废",
          }[value];
        },
      },
    ]);
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 10,
    });
    const rules = reactive({
      applyType: [
        {
          required: true,
          message: "请选择休假类型",
          trigger: "blur",
        },
      ],
      startTime: [
        {
          type: "date",
          required: true,
          message: "请输入开始时间",
          trigger: "blur",
        },
      ],
      endTime: [
        {
          type: "date",
          required: true,
          message: "请输入结束时间",
          trigger: "blur",
        },
      ],
      reasons: [
        {
          required: true,
          message: "请输入休假原因",
          trigger: ["blur", "change"],
        },
      ],
      deptId: [
        {
          required: true,
          message: "请选择部门",
          trigger: "change",
        },
      ],
      mobile: [
        {
          required: true,
          message: "请输入正确的手机格式",
          trigger: "blur",
          pattern: /1[3-9]\d{9}/,
        },
      ],
    });

    const leaveList = ref([]);
    const getLeaveList = async () => {
      let params = { ...queryForm, ...pager };
      const res = await proxy.$api.getLeaveList(params);
      leaveList.value = res.list;
      pager.total = res.page.total;
    };

    const dialogFormVisible = ref(false);
    const action = ref("create");
    const handleApply = () => {
      dialogFormVisible.value = true;
      action.value = "create";
    };

    const leaveForm = reactive({
      applyType: 1,
      startTime: "",
      endTime: "",
      leaveTime: "0天",
      reasons: "",
    });

    const handleClose = () => {
      dialogFormVisible.value = false;
      handleReset("dialogForm");
    };

    const handleSubmit = () => {
      proxy.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          try {
            let parmas = { ...leaveForm, action:'create' };
            await proxy.$api.leaveOperate(parmas);
            proxy.$message.success("创建成功");
            handleClose();
            getLeaveList();
          } catch (error) {}
        }
      });
    };

    const showDetailModel = ref(false);
    const detail = ref({});
    const handleDetail = (row) => {
      showDetailModel.value = true;
      let data = { ...row };
      data.applyTypeName = {
        1: "事假",
        2: "调休",
        3: "年假",
      }[data.applyType];
      data.time =
        utils.formateDate(new Date(data.startTime), "yyyy-MM-dd") +
        "到" +
        utils.formateDate(new Date(data.endTime), "yyyy-MM-dd");

      data.applyStateName = {
        1: "待审批",
        2: "审批中",
        3: "审批拒绝",
        4: "审批通过",
        5: "作废",
      }[data.applyState];

      detail.value = data;
    };
    return {
      detail,
      handleDetail,
      showDetailModel,
      handleDateChange,
      handleSubmit,
      action,
      handleClose,
      leaveForm,
      column,
      pager,
      rules,
      handleQuery,
      handleReset,
      handleCurrentChange,
      handleDelete,
      handleSelectionChange,
      leaveList,
      queryForm,
      handleApply,
      getLeaveList,
      dialogFormVisible,
    };
  },
};
</script>

<style>
.table-btn {
  padding: 20px;
}
</style>